//
// Created by libtity on 24-5-24.
//
#include <arpa/inet.h>
#include <cstring>   // For string operations
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>   // For close()

#define PORT      6666
#define SERVER_IP "192.168.1.8"   // 服务器 IP 地址

using namespace std;

int main()
{
    // 创建客户端 socket
    int client_socket = socket(AF_INET, SOCK_STREAM, 0);
    if ( client_socket == -1 ) {
        cerr << "Failed to create client socket" << endl;
        return 1;
    }

    // 设置服务器地址结构
    sockaddr_in server_addr{};
    server_addr.sin_family      = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
    server_addr.sin_port        = htons(PORT);

    // 连接到服务器
    if ( connect(client_socket, (sockaddr*)&server_addr, sizeof(server_addr)) == -1 ) {
        cerr << "Failed to connect to server" << endl;
        close(client_socket);
        return 1;
    }

    cout << "连接到服务器成功！" << endl;

    // 向服务器发送消息
    const char* message    = "Hello, Server!";
    ssize_t     bytes_sent = send(client_socket, message, strlen(message), 0);
    if ( bytes_sent == -1 ) {
        cerr << "Failed to send message" << endl;
        close(client_socket);
        return 1;
    }

    // 接收服务器的响应消息
    char buffer[1024];
    memset(buffer, 0, sizeof(buffer));
    ssize_t bytes_received = recv(client_socket, buffer, sizeof(buffer), 0);
    if ( bytes_received == -1 ) {
        cerr << "Failed to receive response" << endl;
        close(client_socket);
        return 1;
    }

    cout << "收到服务器的响应：" << buffer << endl;

    // 关闭客户端 socket 连接
    close(client_socket);

    return 0;
}
